using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO; //System.IO is not used by default

namespace CSVParser
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            List<string[]> testParse = parseCSV("C:\\SVNProjects\\CSVTest\\CSVParser\\CSV Files\\RunTimeData_All.csv"); //C:\\SVNProjects\\CSVTest\\CSVParser\\CSV Files\\
            DataTable newTable = new DataTable();

            foreach (string column in testParse[0])
            {
                newTable.Columns.Add(column);
            }

            for (int i = 1; i < testParse.Count; i++)
            {
                newTable.Rows.Add(testParse[i]);
            }
            dataGridView1.DataSource = newTable;
        }

        public List<string[]> parseCSV(string path)
        {
            List<string[]> parsedData = new List<string[]>();

            using (StreamReader readFile = new StreamReader(path))
            {
                string line;
                string[] row;

                while ((line = readFile.ReadLine()) != null)
                {
                    row = line.Split(',');
                    parsedData.Add(row);
                }
            }

            return parsedData;
        }

        public class CsvRow : List<string>
        {
            public string LineText { get; set; }
        }

        public class CsvFileWriter : StreamWriter
        {
            public CsvFileWriter(Stream stream)
                : base(stream)
            {
            }

            public CsvFileWriter(string filename)
                : base(filename)
            {
            }

            /// <summary>
            /// 
            /// </summary>
            /// <param name="row"></param>
            public void WriteRow(CsvRow row)
            {
                StringBuilder builder = new StringBuilder();
                foreach (string value in row)
                {
                    // Add separator if this isn't the first value
                    if (builder.Length > 0)
                        builder.Append(',');

                    if (value.IndexOfAny(new char[] { '"', ',' }) != -1)
                    {
                        // Special handling for values that contain comma or quote
                        // Enclose in quotes and double up any double quotes
                        builder.AppendFormat("\"{0}\"", value.Replace("\"", "\"\""));
                    }
                    else builder.Append(value);
                }
                row.LineText = builder.ToString();
                WriteLine(row.LineText);
            }
        }

        public class CsvFileReader : StreamReader
        {
            public CsvFileReader(Stream stream)
                : base(stream)
            {
            }

            public CsvFileReader(string filename)
                : base(filename)
            {
            }

            /// <summary>
            /// Reads a row of data from a CSV file
            /// </summary>
            /// <param name="row"></param>
            /// <returns></returns>
            public bool ReadRow(CsvRow row)
            {
                row.LineText = ReadLine();
                if (String.IsNullOrEmpty(row.LineText))
                    return false;

                int pos = 0;
                int rows = 0;

                while (pos < row.LineText.Length)
                {
                    string value;

                    // Special handling for quoted field
                    if (row.LineText[pos] == '"')
                    {
                        // Skip initial quote
                        pos++;

                        // Parse quoted value
                        int start = pos;
                        while (pos < row.LineText.Length)
                        {
                            // Test for quote character
                            if (row.LineText[pos] == '"')
                            {
                                // Found one
                                pos++;

                                // If two quotes together, keep one
                                // Otherwise, indicates end of value
                                if (pos >= row.LineText.Length || row.LineText[pos] != '"')
                                {
                                    pos--;
                                    break;
                                }
                            }
                            pos++;
                        }
                        value = row.LineText.Substring(start, pos - start);
                        value = value.Replace("\"\"", "\"");
                    }
                    else
                    {
                        // Parse unquoted value
                        int start = pos;
                        while (pos < row.LineText.Length && row.LineText[pos] != ',')
                            pos++;
                        value = row.LineText.Substring(start, pos - start);
                    }

                    // Add field to list
                    if (rows < row.Count)
                        row[rows] = value;
                    else
                        row.Add(value);
                    rows++;

                    // Eat up to and including next comma
                    while (pos < row.LineText.Length && row.LineText[pos] != ',')
                        pos++;
                    if (pos < row.LineText.Length)
                        pos++;
                }
                // Delete any unused items
                while (row.Count > rows)
                    row.RemoveAt(rows);

                // Return true if any columns read
                return (row.Count > 0);
            }
        }

        private void btn_Write_data_Click(object sender, EventArgs e)
        {
            DataGridViewColumn newColumn = new DataGridViewColumn(dataGridView1.Columns[0].CellTemplate);
            newColumn.Name = "Hex_Data";
            dataGridView1.Columns.Add(newColumn);
        }

        private void btnSaveData_Click(object sender, EventArgs e)
        {
            //void WriteTest()
            //{
                // Write sample data to CSV file
                using (CsvFileWriter writer = new CsvFileWriter("C:\\WriteTest.csv"))
                {
                    CsvRow headerRow = new CsvRow();
                    foreach (DataGridViewColumn dgColumn in dataGridView1.Columns)
                    {
                        headerRow.Add(dgColumn.Name);
                    }
                    writer.WriteRow(headerRow);

                    foreach (DataGridViewRow dgRow in dataGridView1.Rows)
                    {
                        CsvRow row = new CsvRow();

                        foreach (DataGridViewCell cell in dgRow.Cells)
                        {
                            string str = (string)cell.FormattedValue;
                            row.Add(str);
                        }
                        writer.WriteRow(row);
                    }
                    
                    //for (int i = 0; i < 100; i++)
                    //{
                    //    CsvRow row = new CsvRow();
                    //    for (int j = 0; j < 5; j++)
                    //        row.Add(String.Format("Column{1}, row{0}", j));
                    //    writer.WriteRow(row);
                    //}
                }
            //}
        }

    }
}